<?php
/*
 * Capa formulario para agregar pacientes.
 * @Autor: Andrés Ubilla 
 */
class Agregar extends TPage {
    
    public function onLoad($param){
        parent::onLoad($param);
        if(!$this->IsPostBack){
            $this->validarSession();
            $this->iniciarControles();
        }
    }
    
    private function validarSession(){
        $oUsuario = Util::getSession("Usuario");
        if (Util::isNullOrEmpty($oUsuario)) {
            $this->Response->redirect($this->Service->constructUrl("Home"));
        }
    }
    
    private function iniciarControles(){
        $this->setearValidacionForm();
    }
    
    private function setearValidacionForm(){
        $this->imgPaciente->ImageUrl = "./themes/default/img/fotos/masculino.jpg";
        $this->txtRut->Attributes->Add("required","required");
        $this->txtRut->Attributes->Add("Placeholder","15555555-5");
        $this->txtRut->Attributes->Add("minlength","10");
        $this->txtRut->Attributes->Add("maxlength","10");    
        $this->txtEmail->Attributes->Add("type","email");
        $this->txtEmail->Attributes->Add("required","required");
        $this->txtNombre->Attributes->Add("required","required");
        $this->txtFechaNacimiento->Attributes->Add("Placeholder","dd/mm/aaaa");
        $this->txtFechaNacimiento->Attributes->Add("required","required");
        $this->txtFechaNacimiento->Attributes->Add("data-date-format","dd/mm/yyyy");
        $this->ddlSexo->Attributes->Add("required","required");        
        $this->txtPassword2->Attributes->Add("data-validation-matches-match","ctl0\$cphMain\$txtPassword");
        $this->txtPassword2->Attributes->Add("data-validation-matches-message","Las contrase&ntilde;as deben ser iguales");    
    }
    
    public function btnRegistrarPacienteOnClick($sender, $param){
        $urlImg = $this->imgPaciente->ImageUrl;
        
        try{            
            $oPaciente = new Paciente();

            $oPaciente->setRut($this->txtRut->Text);
            $oPaciente->setEmail($this->txtEmail->Text);
            $oPaciente->setNombre($this->txtNombre->Text);
            $oPaciente->setApellido($this->txtApellido->Text);
            $oPaciente->setSexo($this->ddlSexo->SelectedValue);
            $oPaciente->setTelefono($this->txtTelefono->Text);
            $oPaciente->setFechaNacimiento(Util::fechaNormalADateTime($this->txtFechaNacimiento->Text));
            $oPaciente->setActividad($this->txtActividad->Text);
            $oPaciente->setPassword($this->txtPassword->Text);
            if($urlImg == "" && $this->ddlSexo->SelectedValue == 1){
                $oPaciente->setImagen("./themes/default/img/fotos/masculino.jpg");
            }else if($urlImg == "" && $this->ddlSexo->SelectedValue == 2){
                $oPaciente->setImagen("./themes/default/img/fotos/femenino.jpg");
            }else{
                $oPaciente->setImagen($urlImg);
            }            
            $oPaciente->setEstado(1);

            $oPacienteBLL = new PacienteBLL();
            $idPaciente = $oPacienteBLL->grabar($oPaciente);

            if(is_int($idPaciente) && $idPaciente > 0){
                $this->limpiarForm();
                $this->litAlert->Text = Util::setMensajeUsuario("Paciente registrado exitosamente.", Util::MENSAJE_OK);
            }else{
                $this->litAlert->Text = Util::setMensajeUsuario("Error al registrar al paciente, vuelva a intentarlo.", Util::MENSAJE_ERROR);                
            }
        } catch (Exception $e){
            $oPacienteBLL->eliminar($idPaciente);
            throw new Exception($e->getMessage());
        }
    }
    
    private function limpiarForm(){
        $this->txtRut->Text = "";
        $this->txtEmail->Text = "";
        $this->txtNombre->Text = "";
        $this->txtApellido->Text = "";
        $this->ddlSexo->SelectedValue = "";
        $this->txtTelefono->Text = "";
        $this->txtFechaNacimiento->Text = "";
        $this->txtPassword->Text = "";
    } 
    
    public function subirImagenPaciente($sender, $param){
        $ThumbSquareSize = 180;
        $ThumbPrefix = "paciente_";
        $DestinationDirectory = './themes/default/img/fotos/';
        $Quality = 90;
        $RandomNumber = rand(0, 9999999999);
        
        $ImageName = str_replace(' ','-',strtolower($sender->FileName)); 
        $ImageSize = $sender->FileSize;
        $TempSrc = $sender->LocalName;
        $ImageType = $sender->FileType;
        
        switch(strtolower($ImageType)){
            case 'image/png':
                $CreatedImage =  imagecreatefrompng($TempSrc);
                break;
            case 'image/gif':
                $CreatedImage =  imagecreatefromgif($TempSrc);
                break;			
            case 'image/jpeg':
            case 'image/pjpeg':
                $CreatedImage = imagecreatefromjpeg($TempSrc);
                break;
            default:
                $this->lblMensaje->Text = 'Archivo no soportado';
        }
        
        list($CurWidth, $CurHeight) = getimagesize($TempSrc);
        $ImageExt = substr($ImageName, strrpos($ImageName, '.'));
        $ImageExt = str_replace('.','',$ImageExt);
        $ImageName = preg_replace("/\\.[^.\\s]{3,4}$/", "", $ImageName);
        
        $NewImageName = $RandomNumber.'.'.$ImageExt;
        $thumb_DestRandImageName = $DestinationDirectory.$ThumbPrefix.$NewImageName; //Thumb name

        if(!$this->cropImage($CurWidth, $CurHeight, $ThumbSquareSize, $thumb_DestRandImageName, $CreatedImage, $Quality, $ImageType)){
            $this->lblMensaje->Text = 'Error al subir imagen.';
        }else{
            $this->imgPaciente->ImageUrl = "$thumb_DestRandImageName";
        }              
    }
        
    private function cropImage($CurWidth,$CurHeight,$iSize,$DestFolder,$SrcImage,$Quality,$ImageType){	 
        if($CurWidth <= 0 || $CurHeight <= 0){
            return false;
        }

        if($CurWidth>$CurHeight){
            $y_offset = 0;
            $x_offset = ($CurWidth - $CurHeight) / 2;
            $square_size 	= $CurWidth - ($x_offset * 2);
        }else{
            $x_offset = 0;
            $y_offset = ($CurHeight - $CurWidth) / 2;
            $square_size = $CurHeight - ($y_offset * 2);
        }
        
        $NewCanves = imagecreatetruecolor($iSize, $iSize);	
        if(imagecopyresampled($NewCanves, $SrcImage,0, 0, $x_offset, $y_offset, $iSize, $iSize, $square_size, $square_size)){
            
            switch(strtolower($ImageType)){
                case 'image/png':
                        imagepng($NewCanves,$DestFolder);
                        break;
                case 'image/gif':
                        imagegif($NewCanves,$DestFolder);
                        break;			
                case 'image/jpeg':
                case 'image/pjpeg':
                        imagejpeg($NewCanves,$DestFolder,$Quality);
                        break;
                default:
                    return false;
            }
        
        //Destroy image, frees memory	
        if(is_resource($NewCanves)){
            imagedestroy($NewCanves);
        }
            return true;
        }
    }
}
?>
